package com.kye.express.business.jd.search_list.search_result;

import android.databinding.DataBindingUtil;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.jd.goods_detail.JDGoodsDetailActivity;
import com.kye.express.databinding.ActivityJdSearchResultBinding;
import com.kye.express.utils.IntentUtil;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.GridSpacingItemDecoration;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jd.shop.JDGoodsItemBean;
import com.kye.model.bean.jd.shop.JDGoodsListResultBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 京东兑换-搜索-结果页面 Activity
 * <p>
 * Created by SkyYu on 2018/1/29
 */
public class JDGoodsSearchResultActivity extends BaseAppCompatActivity implements JDGoodsSearchResultContract.JDGoodsSearchResultView, JDGoodsSearchResultViewBinder.OnGoodsItemListener {

    private ActivityJdSearchResultBinding mBinding;
    private JDGoodsSearchResultContract.JDGoodsSearchResultPresenter mPresenter;
    private MultiTypeAdapter mAdapter;

    private String phone = "";
    private String goodsName = "";
    public int pageIndex = PageInfo.INDEX_DEFAULT;
    private int pageSize = PageInfo.SIZE_DEFAULT;
    private String kySign = "123456";

    public static void startActivity(String searchResult) {
        IntentUtil.showIntent(JDGoodsSearchResultActivity.class, Constants.KEY_SEARCHRESULT, searchResult);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentValue();
        initViews();
        initData();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) mPresenter.unbind();
    }

    private void getIntentValue() {
        goodsName = getIntent().getStringExtra(Constants.KEY_SEARCHRESULT);
    }

    private void initViews() {
        initDataBinding();
        initToolbar();
    }

    private void initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_jd_search_result);
    }

    private void initToolbar() {
        ToolbarManager.setToolbar(this, mBinding.toolbarJdSearchResult);
        setTitle(goodsName);
    }

    private void initData() {
        initPresenter();
        initAdapter();
    }

    private void initPresenter() {
        mPresenter = new JDGoodsSearchResultContract.JDGoodsSearchResultPresenter();
        mPresenter.bind(this);
    }

    private void initAdapter() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(JDGoodsItemBean.class, new JDGoodsSearchResultViewBinder(this));
        mAdapter.setItems(new Items());
        mBinding.recyclerviewJdSearchResult.setLayoutManager(new GridLayoutManager(this, 2));
        mBinding.recyclerviewJdSearchResult.addItemDecoration(new GridSpacingItemDecoration(2, 5, false));
        mBinding.recyclerviewJdSearchResult.setItemAnimator(new DefaultItemAnimator());
        mBinding.recyclerviewJdSearchResult.setAdapter(mAdapter);
    }

    private void initEvent() {
        mBinding.refreshLayoutJdSearchResult.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                request(false, true, false, phone, goodsName, 1, pageSize, kySign);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                request(false, false, true, phone, goodsName, pageIndex, pageSize, kySign);
            }
        });

        RxView.clicks(mBinding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statusLayoutJdSearchResult.showLoadingView();
                    request(false, true, false, phone, goodsName, 1, pageSize, kySign);
                });
        RxView.clicks(mBinding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statusLayoutJdSearchResult.showLoadingView();
                    request(false, true, false, phone, goodsName, 1, pageSize, kySign);
                });
        RxView.clicks(mBinding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.statusLayoutJdSearchResult.showLoadingView();
                    request(false, true, false, phone, goodsName, 1, pageSize, kySign);
                });
    }

    private void request(boolean isFirstIn, boolean isReFresh, boolean isLoadMore, String phone, String goodsName, int pageIndex, int pageSize, String kySign) {
        NetworkMonitorUtils.networkObservable(this)
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        mPresenter.requestToJDGoodsList(isFirstIn, isReFresh, isLoadMore, phone, goodsName, pageIndex, pageSize, kySign);
                    } else {
                        mBinding.statusLayoutJdSearchResult.showErrorNetworkView();
                        ToastManager.showCenterForLong(getString(R.string.common_net_error));
                    }
                });
    }

    void resetCurrentPageIndex() {
        setCurrentPageIndex(1);
    }

    void setCurrentPageIndex(int currentPage) {
        pageIndex = currentPage;
    }

    @Override
    public void onLoadUser(User user) {
        phone = user.getPhone();
        request(true, false, false, phone, goodsName, pageIndex, pageSize, kySign);
    }

    @Override
    public void onCompleteJDGoodsList(boolean isLoadMore) {
        if (isLoadMore) {
            mBinding.refreshLayoutJdSearchResult.finishLoadmore();
        } else {
            mBinding.refreshLayoutJdSearchResult.finishRefresh();
        }
    }

    @Override
    public void onSuccessJDGoodsList(OpenApiResult<JDGoodsListResultBean> bean, boolean isFirstIn, boolean isReFresh, boolean isLoadMore) {
        if (bean != null) {
            if (bean.getCode() == Constants.ResponseCode_SUCCESS) {
                List<JDGoodsItemBean> tempData = bean.getData().getDatas();
                if (tempData.size() > 0) {
                    mBinding.statusLayoutJdSearchResult.showContentView();

                    Items data = (Items) mAdapter.getItems();
                    if (!isLoadMore) {
                        data.clear();
                        data.addAll(tempData);
                        mAdapter.setItems(data);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        data.addAll(tempData);
                        int start = tempData.size();
                        mAdapter.notifyItemRangeChanged(start, data.size());
                    }

                    if (isReFresh) {
                        resetCurrentPageIndex();
                    }
                    setCurrentPageIndex(pageIndex + 1);
                } else {
                    if (isFirstIn) {
                        mBinding.statusLayoutJdSearchResult.getEmptyTextView();
                    } else {
                        ToastManager.showCenterForShort(getString(R.string.common_no_more_datas));
                    }
                }
                if(tempData.size() < pageSize){
                    mBinding.refreshLayoutJdSearchResult.setEnableLoadmore(false);
                }
            } else {
                if (isLoadMore) {
                    ToastManager.showCenterForShort(getString(R.string.common_no_more_datas));
                } else {
                    ToastManager.showCenterForShort(bean.getMsg());
                }
            }
        } else {
            Logger.d("JDGoodsSearchResultActivity - onSuccessJDGoodsList - bean is null");
        }
    }

    @Override
    public void onApiErrorJDGoodsList(OpenApiResult<JDGoodsListResultBean> result, int code, String msg) {
        mBinding.statusLayoutJdSearchResult.showErrorServerView();
        ToastManager.showCenterForShort(msg);
        Logger.d("JDGoodsSearchResultActivity - onApiErrorJDGoodsList - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onOtherErrorJDGoodsList(Throwable e) {
        ToastManager.showCenterForShort(getString(R.string.common_net_error));
        e.printStackTrace();
    }

    @Override
    public void onGoodsItemClicked(JDGoodsItemBean item) {
        JDGoodsDetailActivity.startActivity(this,item);
    }
}